import javax.swing.*;
import java.util.Arrays;

public class TestHeap {

    public int[] elem;
    public int usedSize;

    public TestHeap(){
        this.elem = new int[10];
    }

    public void initElem(int[] array){//初始化堆
        for (int i = 0; i < array.length; i++) {
            this.elem[i] = array[i];
            this.usedSize++;
        }
    }

    public void createHeap(){//创建堆 以大根堆为例
        for (int parent = (this.usedSize-1-1)/2; parent >= 0; parent--) {
            siftDowm(parent,this.usedSize);
        }
    }

    //向下建堆
    //parent每棵子树调整的时候的起始位置  usedSize判断每棵子树什么时候调整结束
    public void siftDowm(int parent, int usedSize){
        int child = 2*parent+1;//左孩子结点、、、右孩子结点为2*parent+2
        while (child<usedSize){
            //找到左右孩子的最大值
            if (child + 1 < usedSize && elem[child] < elem[child+1]) {
                child++;
            }
            if (elem[child] >elem[parent]){
                swap(elem,child,parent);
                parent = child;
                child = 2*parent+1;
            }else {
                break;
            }
        }
    }

    public void swap (int[] elem,int i, int j){
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }

    //向上建堆
    public void siftUp(int child){
        int parent = (child-1)/2;
        while (parent >= 0) {

            if (elem[child] > elem[parent]){
                swap(elem,child,parent);
                child = parent;
                parent = (child - 1)/2;
            }else{
                break;
            }
        }
    }

    //插入
    public void offer(int val){
        if (isFull()){
            elem = Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize] = val;
        siftUp(usedSize);
        usedSize++;
    }

    //判满
    public boolean isFull(){
        return usedSize == elem.length;
    }

    //判空
    public boolean isEmpty(){
        return usedSize == 0;
    }

    //删除堆顶元素
    public int poll(){
        if (isEmpty()){
            return -1;
        }
        int val = elem[0];
        swap(elem,0,usedSize-1);
        siftDowm(0,usedSize-1);
        usedSize--;
        return val;
    }

    //打印堆顶元素
    public int peek(){
        if (isEmpty()){
            return -1;
        }
        return elem[0];
    }

    //堆排序//从小到大用大根堆  从大到小用小根堆
    public void heapSort(){
        int end = usedSize-1;
        while (end>0){
            swap(elem,0,end);
            siftDowm(0,end );
            end--;
        }
    }

}
